package com.example.reception.service;

import com.example.reception.dao.ProductsDao;
import com.example.reception.entity.Products;
import com.example.system.model.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

/**
 * @author: adnaan
 * @create: 2023-10-20 10:05
 * @Description:
 */
@Service
public class ProductsService {
    @Autowired
    private ProductsDao ProductsDao;

    public ApiResponse findByType(String productId) {
        Criteria criteriaType = Criteria.where("id").is(productId);
        Criteria orCriteria = new Criteria();
        orCriteria.orOperator(criteriaType);
        Query query = new Query(orCriteria);
        if (query != null) {
            return ApiResponse.success(ProductsDao.get(query));
        } else {
            return ApiResponse.error("500", "获取失败");
        }
    }

    public ApiResponse findPaginated(int pageNum, int pageSize, String name) {
        return ProductsDao.findPaginated(pageNum, pageSize, name);
    }

    public Products findDetail(String id) {
        return ProductsDao.findDetail(id);
    }

    public ApiResponse addProduct(Products products) {
        return ProductsDao.addProduct(products);
    }

    public ApiResponse delProduct(String productId) {
        Query query = new Query(Criteria.where("id").is(productId));
        return ProductsDao.delete(query);
    }

    public ApiResponse updateProduct(Products products) {
        Query query = new Query(Criteria.where("id").is(products.getId()));
        Update update=new Update();
        update.set("name",products.getName());
        update.set("price",products.getPrice());
        update.set("image",products.getImage());
        update.set("description",products.getDescription());
        return ProductsDao.update(query,update);
    }

    public ApiResponse hotProducts() {
        return ProductsDao.hotGet();
    }

    public ApiResponse saveCart(String username, String productId, Integer quantity) {
        String shopping_redis = "shopping_cart:" + username;
        return ProductsDao.redisHashAdd(shopping_redis,productId,quantity);
    }

    public ApiResponse delCart(String username,String productId) {
        String shopping_redis = "shopping_cart:" + username;
        return ProductsDao.redisHashClear(shopping_redis,productId);
    }

    public ApiResponse getCartContents(String username) {
        String shopping_redis = "shopping_cart:" + username;
        return ProductsDao.redisHashGet(shopping_redis);
    }
}
